
#include "Sound.h"

namespace Engine {

namespace Synaptic {

bool Sound::initialized = false; // Tells if the Sound system is initialized
std::map<std::string, Mix_Chunk *> Sound::soundMap; 
// Load a sound into memmory
bool Sound::loadSound(std::string name) throw(const char *)
{
	if (!initialized) {
		int audio_rate = 22050;
		Uint16 audio_format = AUDIO_S16; 
		int audio_channels = 2;
		int audio_buffers = 4096;
		if (Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers) != 0) {
			throw "Unable to open audio/SDL_Mixer!";
		}
		initialized = true;
	}
	if (soundMap.find(name) != soundMap.end()) return true;
	Mix_Chunk * tmpChunk = Mix_LoadWAV(name.c_str());
	if (!tmpChunk) throw Mix_GetError();
	soundMap[name] = tmpChunk;
	return true;
}

// Try to play a audio chunk. Returns the channel number
Sint16 Sound::play(std::string name, int loops)
{
	if (!initialized) return -3;
	if (soundMap.find(name) == soundMap.end()) return -2;
	Mix_Chunk * chunk = soundMap[name];
	return Mix_PlayChannel(-1, chunk, loops);
}

// Stop playing an audio channel
bool Sound::stop(Sint16 channel)
{
	Mix_HaltChannel(channel);
	return true;
}


} // namespace Engine::Synaptic

} // namespace Engine
